import { IQueue, IQueueIterator } from "./types";
import Stack from '@/sources/Stack/useSl'

// 队列
export default class Queue<T = number> implements IQueue<T> {
    private inStack: Stack<T>
    private outStack: Stack<T>
    constructor() {
        // 初始化Stack
        this.inStack = new Stack<T>()
        this.outStack = new Stack<T>()
    }

    /**
     * 获取队列的长度
     */
    size() {
        return this.inStack.size() + this.outStack.size()
    }

    /**
     * 判断队列是否为空
     */
    isEmpty() {
        return this.size() === 0
    }

    /**
     * 清空队列元素
     */
    clear() {
        this.inStack.clear()
        this.outStack.clear()
    }

    /**
     * 入队
     * @param element 
     */
    enQueue(element: T) {
        this.inStack.push(element)
    }

    /**
     * 出队
     */
    deQueue() {
        this.inToOut();
        return this.outStack.pop()
    }

    /**
     * 获取队头元素
     */
    front() {
        this.inToOut()

        // 从outStack中弹出
        return this.outStack.top();
    }

    /**
     * 将inStack中压入outStack中
     */
    private inToOut() {
        // inStack不为空， 一直取出，压入outStack中
        while (!this.inStack.isEmpty()) {
            this.outStack.push(this.inStack.pop()!)
        }
    }

    /**
     * 遍历队列
     */
    forEach(cb: IQueueIterator<T>) {
        while(!this.outStack.isEmpty()) {
            this.inStack.push(this.outStack.pop()!)
        }
        this.inStack.forEach((ele, i) => {
            cb(ele, i)
            return false
        })
    }
} 